package game.views;

import hx.utils.SoundManager;
import hx.events.Event;
import game.modes.ModeManage;
import game.data.XlsData;
import hx.display.ArrayCollection;
import hx.utils.SceneManager;
import hx.display.UILoadScene;

/**
 * 地图选择界面
 */
@:build(hx.macro.UIBuilder.build("assets/views/MapSelectView.xml"))
class MapSelectView extends UILoadScene {
	override function onLoaded() {
		super.onLoaded();
		this.back.clickEvent = function() {
			SceneManager.getInstance().backScene(true);
		};
		// 地图数据内容
		var array = new ArrayCollection([
			for (item in XlsData.maps.data) {
				{
					text: item.name,
					data: item
				}
			}
		]);
		for (index => value in array.source) {
			var item = new MapIconItem();
			this.hbox.addChild(item);
			item.setData(value);
			item.setSelected(index == 0);
		}
		this.mapSelect.setData(array);
		this.ok.clickEvent = () -> {
			ModeManage.currentReadyWorld.mapId = this.mapSelect.selectedItem.data.mapid;
			ModeManage.attackWorld();
			SoundManager.getInstance().playEffect("selected");
		}
		this.mapSelect.addEventListener(Event.CHANGE, onMapSelected);
		this.updateEnabled = true;
		onMapSelected(null);
	}

	public var currentMapIconItem:MapIconItem;

	private function onMapSelected(e:Event):Void {
		for (index => object in hbox.children) {
			if (object is MapIconItem) {
				var map:MapIconItem = cast object;
				map.setSelected(mapSelect.selectedIndex == index);
				if (mapSelect.selectedIndex == index) {
					currentMapIconItem = map;
				}
			}
		}
	}

	override function onUpdate(dt:Float) {
		super.onUpdate(dt);
		if (currentMapIconItem == null)
			return;
		var targetX = -(this.currentMapIconItem.x + 767 * 0.5) * 0.7 + stage.stageWidth / 2;
		hbox.x += (targetX - hbox.x) * 0.1;
	}
}
